const Realm = require('realm')
const { VersionSchema, IntValueSchema } = require('./version')
const { AppSchema } = require('./app')
const schemas = {
  5: { schema: [VersionSchema, AppSchema] },
  6: { schema: [VersionSchema, AppSchema] },
  7: { schema: [VersionSchema, AppSchema] },
  8: { schema: [VersionSchema, AppSchema] },
  10: { schema: [VersionSchema, AppSchema] },
  11: { schema: [VersionSchema, AppSchema, IntValueSchema] },
  12: { schema: [VersionSchema, AppSchema, IntValueSchema] },
  13: { schema: [VersionSchema, AppSchema, IntValueSchema] }
}
const realm = new Realm({
  path: '../realmDB',
  schema: [VersionSchema, AppSchema, IntValueSchema],
  schemaVersion: 13,
  migration: (oldRealm, newRealm) => {
    let version = Realm.schemaVersion('../realmDB')
    schemas[version] && schemas[version].schema.forEach(schema => {
      let oldObjects = oldRealm.objects(schema.name)

      let newObjects = newRealm.objects(schema.name)
      for (var i = 0; i < oldObjects.length; i++) {
        Object.assign(oldObjects[i], newObjects[i])
      }
    })
  }
})
module.exports = realm
